package com.jixiang.goods.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jixiang.goods.dao.GsGoodsInfoDao;
import com.jixiang.goods.service.*;
import com.jixiang.model.common.dtos.ResponseResult;
import com.jixiang.model.goods.dtos.*;
import com.jixiang.model.goods.entity.*;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.jixiang.common.constants.GoodsIndexConstants.MAPPING_NAME;
import static com.jixiang.common.constants.GoodsIndexConstants.MAPPING_TEMPLATE;
import static com.jixiang.common.constants.RedisConstants.*;

/**
 * (GsGoodsInfo)表服务实现类
 *
 * @author makejava
 * @since 2023-10-23 20:55:53
 */
@Service("gsGoodsInfoService")
public class GsGoodsInfoServiceImpl extends ServiceImpl<GsGoodsInfoDao, GsGoodsInfo> implements GsGoodsInfoService {
    @Resource
    private GsGoodsInfoService gsGoodsInfoService;
    @Resource
    private GsGoodsStaticCustomParamsService gsGoodsStaticCustomParamsService;
    @Resource
    private GsGoodsStaticParamsService gsGoodsStaticParamsService;
    @Resource
    private GsPicService gsPicService;
    @Resource
    private GsGoodsSpecsService gsGoodsSpecsService;
    @Resource
    private GsGoodsSpecsValueService gsGoodsSpecsValueService;
    @Resource
    private GsGoodsSkusService gsGoodsSkusService;
    @Resource
    private GsGoodsSkusValueService gsGoodsSkusValueService;
    @Resource
    private GsGoodsBrankService gsGoodsBrankService;
    @Resource
    private GsGoodsSelectService gsGoodsSelectService;
    @Resource
    private GsGoodsTypeService gsGoodsTypeService;

    @Resource
    private GoodsEsService goodsEsService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource
    RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("goods.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @Override
    public ResponseResult adminAddGoods(GoodsAddDtos goodsDtos) {
        GsGoodsInfo gsGoodsInfo = new GsGoodsInfo();
        gsGoodsInfo.setName(goodsDtos.getName());
        gsGoodsInfo.setOldPrice(goodsDtos.getOldPrice());
        gsGoodsInfo.setPrice(goodsDtos.getPrice());
        gsGoodsInfo.setNum(goodsDtos.getNum());
        gsGoodsInfo.setWeight(goodsDtos.getWeight());
        gsGoodsInfo.setInventory(goodsDtos.getInventory());
        gsGoodsInfo.setGoodsTypeId(Long.valueOf(goodsDtos.getGoodsType()));
        gsGoodsInfo.setGoodsSelectId(Long.valueOf(goodsDtos.getGoodsSelect()));
        gsGoodsInfo.setGoodsBrankId(Long.valueOf(goodsDtos.getGoodsBrank()));
        gsGoodsInfo.setDynamicParamState(goodsDtos.getDynamicParam());
        gsGoodsInfo.setMainPic(goodsDtos.getMainPic());
        gsGoodsInfo.setGoodsState(goodsDtos.getGoodsState());
        boolean save = gsGoodsInfoService.save(gsGoodsInfo);
        Long goodsId = gsGoodsInfo.getId();
        goodsEsService.saveEsGoodsById(gsGoodsInfo.getId());
        GsGoodsStaticParams gsGoodsStaticParams = new GsGoodsStaticParams();
        gsGoodsStaticParams.setGoodsId(goodsId);
        gsGoodsStaticParams.setModel(goodsDtos.getModel());
        gsGoodsStaticParams.setCertificateNo(goodsDtos.getCertificateNo());
        gsGoodsStaticParams.setProduction(goodsDtos.getProduction());
        gsGoodsStaticParams.setIntroduce(goodsDtos.getIntroduce());
        gsGoodsStaticParams.setSuitAge(goodsDtos.getSuitAge());
        gsGoodsStaticParams.setSuitPer(goodsDtos.getSuitPer());
        gsGoodsStaticParamsService.save(gsGoodsStaticParams);

        if(goodsDtos.getAddStaticCustomList() != null &&(!goodsDtos.getAddStaticCustomList().isEmpty())) {
            goodsDtos.getAddStaticCustomList().forEach(item ->{
                GsGoodsStaticCustomParams gsGoodsStaticCustomParams = new GsGoodsStaticCustomParams();
                gsGoodsStaticCustomParams.setGoodsId(goodsId);
                gsGoodsStaticCustomParams.setParamKey(item.getKeyName());
                gsGoodsStaticCustomParams.setParamValue(item.getValueName());
                gsGoodsStaticCustomParamsService.save(gsGoodsStaticCustomParams);
            });
        }

        if(goodsDtos.getListPic() != null &&(!goodsDtos.getListPic().isEmpty())) {
            goodsDtos.getListPic().forEach(item ->{
                GsPic gsPic = new GsPic();
                gsPic.setGoodsId(goodsId);
                gsPic.setPic(item);
                gsPicService.save(gsPic);
            });
        }

        if(goodsDtos.getDynamicParam() == 0){
            return ResponseResult.okResult("创建成功");
        }

        if(goodsDtos.getSpecsList() != null &&(!goodsDtos.getSpecsList().isEmpty())) {
            goodsDtos.getSpecsList().forEach(SpecsItem ->{
                GsGoodsSpecs gsGoodsSpecs = new GsGoodsSpecs();
                gsGoodsSpecs.setGoodsId(goodsId);
                gsGoodsSpecs.setName(SpecsItem.getName());
                boolean save1 = gsGoodsSpecsService.save(gsGoodsSpecs);
                if(SpecsItem.getValues()!=null && (!SpecsItem.getValues().isEmpty())){
                    SpecsItem.getValues().forEach(SpecsValueItem -> {
                        GsGoodsSpecsValue gsGoodsSpecsValue = new GsGoodsSpecsValue();
                        gsGoodsSpecsValue.setSpecsId(gsGoodsSpecs.getId());
                        gsGoodsSpecsValue.setDes(SpecsValueItem.getDesc());
                        gsGoodsSpecsValue.setName(SpecsValueItem.getName());
                        gsGoodsSpecsValue.setPicture(SpecsValueItem.getPicture());
                        gsGoodsSpecsValueService.save(gsGoodsSpecsValue);
                    });
                }
            });
        }

        if(goodsDtos.getSkusList()!=null &&(!goodsDtos.getSkusList().isEmpty())){
            goodsDtos.getSkusList().forEach(skuItem -> {
                if(skuItem.getIsUse() == 1){
                    GsGoodsSkus gsGoodsSkus = new GsGoodsSkus();
                    gsGoodsSkus.setGoodsId(goodsId);
                    gsGoodsSkus.setInventory(skuItem.getInventory());
                    gsGoodsSkus.setPrice(skuItem.getPrice().doubleValue());
                    gsGoodsSkus.setOldPrice(skuItem.getOldPrice().doubleValue());
                    if(StrUtil.isNotBlank(skuItem.getPicture())){
                        gsGoodsSkus.setPicture(skuItem.getPicture());
                    }
                    gsGoodsSkus.setPicture(goodsDtos.getMainPic());

                    boolean save1 = gsGoodsSkusService.save(gsGoodsSkus);
                    if(skuItem.getSpecs() != null && (!skuItem.getSpecs().isEmpty())){
                        skuItem.getSpecs().forEach(item -> {
                            GsGoodsSkusValue gsGoodsSkusValue = new GsGoodsSkusValue();
                            gsGoodsSkusValue.setSkusId(gsGoodsSkus.getId());
                            gsGoodsSkusValue.setValueName(item.getValueName());
                            gsGoodsSkusValue.setName(item.getName());
                            gsGoodsSkusValueService.save(gsGoodsSkusValue);
                        });
                    }
                }
            });
        }
        return ResponseResult.okResult("创建成功");
    }

    @Override
    public ResponseResult adminGetGoodsList(int pageNum, int pageSize, String goodsSelect, String goodsState, String goodsName) {
        PageHelper.startPage(pageNum,pageSize);
        List<GsGoodsInfo> list = query().eq(StrUtil.isNotBlank(goodsSelect), "goods_select_id", goodsSelect).like(StrUtil.isNotBlank(goodsName), "name", goodsName).eq(StrUtil.isNotBlank(goodsState), "goods_state", goodsState).list();
        List<GoodsDto> collect = list.stream().map(item -> {
            GoodsDto goodsDto = getGoodsDto(item);
            return goodsDto;
        }).collect(Collectors.toList());
        PageInfo page = new PageInfo(collect);
        return ResponseResult.okResult(page);
    }


    @Override
    public ResponseResult appGetGoodsListByNew() {
        try {
            SearchRequest searchRequest = new SearchRequest(MAPPING_NAME);
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termQuery("goodsState",1)).must(QueryBuilders.termQuery("goodsSelectId",2));
            searchRequest.source().query(boolQueryBuilder).sort("createTime", SortOrder.DESC);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = response.getHits();
            SearchHit[] hits = searchHits.getHits();
            List<GsGoodsInfo> list =new ArrayList<GsGoodsInfo>();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                GsGoodsInfo gsGoodsInfo = JSON.parseObject(json, GsGoodsInfo.class);
                list.add(gsGoodsInfo);
            }
            return ResponseResult.okResult(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseResult appGetGoodsListByHot() {
        try {
//            goodsEsService.saveEsGoodsById(1716848788108242945L);
            SearchRequest searchRequest = new SearchRequest(MAPPING_NAME);
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termQuery("goodsState",1)).must(QueryBuilders.termQuery("goodsSelectId",1));
            searchRequest.source().query(boolQueryBuilder).sort("createTime", SortOrder.DESC);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = response.getHits();
            SearchHit[] hits = searchHits.getHits();
            List<GsGoodsInfo> list =new ArrayList<GsGoodsInfo>();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                GsGoodsInfo gsGoodsInfo = JSON.parseObject(json, GsGoodsInfo.class);
                list.add(gsGoodsInfo);
            }
            return ResponseResult.okResult(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseResult addGoodsIndex() {
        Boolean b = existsIndex(MAPPING_NAME);
        if(b){
            return ResponseResult.okResult("已存在，无需创建");
        }
        createGoodsIndex();

        Boolean flag = existsIndex(MAPPING_NAME);
        if(flag){
            return ResponseResult.okResult("创建成功");
        }else {
            return ResponseResult.okResult("创建失败");
        }
    }

    private void createGoodsIndex() {
        try {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(MAPPING_NAME);
            createIndexRequest.source(MAPPING_TEMPLATE, XContentType.JSON);
            restHighLevelClient.indices().create(createIndexRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseResult updateGoodsSearch() {
        Boolean b = existsIndex(MAPPING_NAME);
        if(b){
            deleteGoodsIndex(MAPPING_NAME);
        }
        createGoodsIndex();
        Boolean existsIndex = existsIndex(MAPPING_NAME);
        if(!existsIndex){
            return ResponseResult.okResult("创建索引失败");
        }
        try {
            List<GsGoodsInfo> list = query().list();
            BulkRequest bulkRequest = new BulkRequest();
            list.forEach(item -> {
                GsGoodsType gsGoodsType = gsGoodsTypeService.query().eq("id", item.getGoodsTypeId()).list().get(0);
                item.setParentGoodsTypeId(gsGoodsType.getParentGoodsTypeId());
                String jsonObject = JSONUtil.toJsonStr(item);
                bulkRequest.add(new IndexRequest(MAPPING_NAME).id(item.getId().toString()).source(jsonObject,XContentType.JSON));
            });
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.okResult("跟新成功");
    }

    @Override
    public ResponseResult appGetGoodsInfoById(String id) {
//        query().eq("id",id)
        GoodsDto goodsDtosById = getGoodsDtosById(id);
        return ResponseResult.okResult(goodsDtosById);
    }

    @Override
    public ResponseResult appGetGoodsHotByGoodsId(String id, String type) {
        GoodsDto goodsDto = getGoodsDtosById(id);
        List<GsGoodsInfo> list = null;
        try {
            SearchRequest searchRequest = new SearchRequest(MAPPING_NAME);
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termQuery("goodsSelectId", type)).must(QueryBuilders.termQuery("goodsTypeId", goodsDto.getGoodsTypeId()));
            searchRequest.source().query(boolQueryBuilder).sort("createTime", SortOrder.DESC).size(10);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = response.getHits();
            SearchHit[] hits = searchHits.getHits();
            list = new ArrayList<GsGoodsInfo>();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                GsGoodsInfo gsGoodsInfo = JSON.parseObject(json, GsGoodsInfo.class);
                list.add(gsGoodsInfo);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.okResult(list);
    }

    @Override
    public String goodsInventory(List<CartDtos> cartDtosList) {
        List<GsGoodsInfo> list = query().list();
        list.forEach(item -> {
            if(item.getDynamicParamState() == 0){
                stringRedisTemplate.opsForValue().set(REDIS_GOODS_ID + item.getId() + REDIS_SKU_ID + 0,item.getInventory().toString());
            }else {
                List<GsGoodsSkus> gsGoodsSkusList = gsGoodsSkusService.query().eq("goods_id", item.getId()).list();
                if(gsGoodsSkusList!=null || !gsGoodsSkusList.isEmpty()){
                    gsGoodsSkusList.forEach(items -> {
                        stringRedisTemplate.opsForValue().set(REDIS_GOODS_ID + item.getId() + REDIS_SKU_ID + items.getId(),item.getInventory().toString());
                    });
                }
            }
        });
        return "1";
    }

    @Override
    public GoodsDto getGoodsInfoById(String id) {
        GoodsDto goodsDtosById = getGoodsDtosById(id);
        return goodsDtosById;
    }

    @Override
    public ResponseResult wxGetGoodsListByHot() {
        List<GoodsByWxHot> goodsByWxHot = getGoodsByWxHot();
        return ResponseResult.okResult(goodsByWxHot);
    }

    @Override
    public ResponseResult wxGetGoodsListBySelectId(int pageNum, int pageSize, int selectId) {
        GsGoodsSelect gsGoodsSelect = gsGoodsSelectService.query().eq("id", selectId).orderByDesc("priority").list().get(0);
        GoodsListBySelectIdDtos goodsListBySelectIdDtos = new GoodsListBySelectIdDtos();
        goodsListBySelectIdDtos.setSelectName(gsGoodsSelect.getName());
        if(gsGoodsSelect.getId()==0){
            goodsListBySelectIdDtos.setSelectName("平台优选");
        }
        goodsListBySelectIdDtos.setId(gsGoodsSelect.getId());

        SearchRequest searchRequest = new SearchRequest(MAPPING_NAME);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("goodsSelectId", selectId));
        searchRequest.source().query(boolQueryBuilder).sort("createTime", SortOrder.DESC).from((pageNum - 1) * pageSize).size(pageSize);
        double total=0;
        double ceil=1;
        List<GsGoodsInfo> list=new LinkedList<>();
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            total = search.getHits().getTotalHits().value;
            list = handleGoodsResponse(search);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(total);
        System.out.println(pageSize);
        double i = total / pageSize;
        ceil = (int) Math.ceil(total / pageSize);
        goodsListBySelectIdDtos.setPageSum((int)ceil);
        goodsListBySelectIdDtos.setGoodsList(list);
        goodsListBySelectIdDtos.setTotal((int)total);
        return ResponseResult.okResult(goodsListBySelectIdDtos);
    }

    private List<GoodsByWxHot> getGoodsByWxHot() {
        String redisData = stringRedisTemplate.opsForValue().get(REDIS_PREX_WXSELECT);
        if(StrUtil.isNotBlank(redisData)){
            List<GoodsByWxHot> list = JSONUtil.toList(redisData, GoodsByWxHot.class);
            stringRedisTemplate.expire(REDIS_PREX_WXSELECT,REDIS_EXPIRE_WXSELECT,TimeUnit.HOURS);
            return list;
        }
        if(redisData!=null){
            return null;
        }

        RLock lock = redissonClient.getLock(REDIS_LOCK_WXSELECT);
        try {
            boolean tryLock = lock.tryLock(1000,TimeUnit.MILLISECONDS);
            if(!tryLock){
                Thread.sleep(500);
                getGoodsByWxHot();
            }
            List<GoodsByWxHot> GoodsByWxHotlist = new LinkedList<>();
            List<GsGoodsSelect> list = gsGoodsSelectService.query().orderByDesc("priority").list();
            if(list.isEmpty()){
                stringRedisTemplate.opsForValue().set(REDIS_PREX_WXSELECT,"",REDIS_EXPIRE_WXSELECT,TimeUnit.HOURS);
                return  null;
            }
            list.forEach(item -> {
                SearchRequest searchRequest = new SearchRequest(MAPPING_NAME);
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                boolQueryBuilder.must(QueryBuilders.termQuery("goodsSelectId", item.getId()));
                searchRequest.source().query(boolQueryBuilder).sort("createTime", SortOrder.DESC).size(10);
                SearchResponse response = null;
                try {
                    response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                List<GsGoodsInfo> gsGoodsInfos = handleGoodsResponse(response);
               if(!gsGoodsInfos.isEmpty()){
                   GoodsByWxHot goodsByWxHot = new GoodsByWxHot();
                   goodsByWxHot.setId(item.getId());
                   if(item.getName().equals("默认选择类型")){
                       goodsByWxHot.setSelectName("平台优选");
                   }else {
                       goodsByWxHot.setSelectName(item.getName());
                   }
                   goodsByWxHot.setMainPic(gsGoodsInfos.get(0).getMainPic());
                   if(gsGoodsInfos.size()>=2){
                       goodsByWxHot.setSecPic(gsGoodsInfos.get(1).getMainPic());
                   }
                   GoodsByWxHotlist.add(goodsByWxHot);
               }
            });
            JSONArray objects = JSONUtil.parseArray(GoodsByWxHotlist);
            stringRedisTemplate.opsForValue().set(REDIS_PREX_WXSELECT,objects.toString(),REDIS_EXPIRE_WXSELECT,TimeUnit.HOURS);
            return GoodsByWxHotlist;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }

    List<GsGoodsInfo> handleGoodsResponse(SearchResponse search){
        LinkedList<GsGoodsInfo> list = new LinkedList<>();
        SearchHits searchHits = search.getHits();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            GsGoodsInfo gsGoodsInfo = JSON.parseObject(json, GsGoodsInfo.class);
            list.add(gsGoodsInfo);
        }
        return list;
    }

    private void deleteGoodsIndex(String mapping){
        try {
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(mapping);
            restHighLevelClient.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private Boolean existsIndex(String mapping) {
        Boolean exists = false;
        try {
            GetIndexRequest getIndexRequest = new GetIndexRequest(mapping);
            exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return exists;
    }
    public GoodsDto getGoodsDtosById(String id){
        String redisdata = stringRedisTemplate.opsForValue().get(REDIS_PREX_GOODS + id);
        if(StrUtil.isNotBlank(redisdata)){
            GoodsDto bean = JSONUtil.toBean(redisdata, GoodsDto.class);
            return bean;
        }
        if(redisdata!=null){
            return null;
        }
        GoodsDto goodsDto = new GoodsDto();
        RLock lock = redissonClient.getLock(REDIS_LOCK_GOODS);
        try {
            boolean tryLock = lock.tryLock(500, TimeUnit.MILLISECONDS);
            if(!tryLock){
                Thread.sleep(500);
                getGoodsDtosById(id);
            }
            GsGoodsInfo gsGoodsInfo = query().eq("id", id).list().get(0);
            goodsDto = getGoodsDto(gsGoodsInfo);
            setGoodsDtoInv(goodsDto);
            String jsonStr = JSONUtil.toJsonStr(goodsDto);
            stringRedisTemplate.opsForValue().set(REDIS_PREX_GOODS + id,jsonStr,REDIS_EXPIER_GOODS,TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

        return goodsDto;
    }

    private void setGoodsDtoInv(GoodsDto goodsDto) {
        if(goodsDto.getDynamicParamState()==0){
            String inv = stringRedisTemplate.opsForValue().get(REDIS_GOODS_ID + goodsDto.getId().toString() + REDIS_SKU_ID + 0);
            goodsDto.setInventory(Integer.valueOf(inv));
        }else {
            goodsDto.getSkus().forEach(item -> {
                String inv = stringRedisTemplate.opsForValue().get(REDIS_GOODS_ID + goodsDto.getId().toString() + REDIS_SKU_ID + item.getId());
                item.setInventory(Integer.valueOf(inv));
            });
        }
    }

    private GoodsDto getGoodsDto(GsGoodsInfo item) {
        GoodsDto goodsDto = BeanUtil.copyProperties(item, GoodsDto.class);
        Long id = item.getId();
        GsGoodsBrank gsGoodsBrank = gsGoodsBrankService.query().eq("id", item.getGoodsBrankId()).list().get(0);
        goodsDto.setGsGoodsBrank(gsGoodsBrank);
        GsGoodsSelect gsGoodsSelect = gsGoodsSelectService.query().eq("id", item.getGoodsSelectId()).list().get(0);
        goodsDto.setGsGoodsSelect(gsGoodsSelect);
        GsGoodsType gsGoodsType = gsGoodsTypeService.query().eq("id", item.getGoodsTypeId()).list().get(0);
        goodsDto.setGsGoodsType(gsGoodsType);
        GsGoodsType gsGoodsType1 = gsGoodsTypeService.query().eq("id", gsGoodsType.getParentGoodsTypeId()).list().get(0);
//        goodsDto.setSecondGoodsTypeName(gsGoodsType1.);
        goodsDto.setSecondeGoodsType(gsGoodsType1);
        GsGoodsType gsGoodsType2 = gsGoodsTypeService.query().eq("id", gsGoodsType1.getParentGoodsTypeId()).list().get(0);
        goodsDto.setFirstGoodsType(gsGoodsType2);

        GsGoodsStaticParams gsGoodsStaticParams = gsGoodsStaticParamsService.query().eq("goods_id", item.getId()).list().get(0);
        if(gsGoodsStaticParams!=null) {
            goodsDto.setGsGoodsStaticParams(gsGoodsStaticParams);
        }

        List<GsGoodsStaticCustomParams> gsGoodsStaticCustomParams = gsGoodsStaticCustomParamsService.query().eq("goods_id", id).list();
        if(gsGoodsStaticCustomParams!=null && (!gsGoodsStaticCustomParams.isEmpty())){
            goodsDto.setGsGoodsStaticCustomParamsList(gsGoodsStaticCustomParams);
        }
        List<GsPic> gsPicList = gsPicService.query().eq("goods_id", id).list();
        if(gsPicList!= null &&(!gsPicList.isEmpty())){
            goodsDto.setPicList(gsPicList);
        }

        if(item.getDynamicParamState()==0){
            return goodsDto;
        }
        List<GsGoodsSpecs> gsGoodsSpecsList = gsGoodsSpecsService.query().eq("goods_id", id).list();
        if (gsGoodsSpecsList!=null &&(!gsGoodsSpecsList.isEmpty())){
            gsGoodsSpecsList.forEach(items -> {
                List<GsGoodsSpecsValue> gsGoodsSpecsValues = gsGoodsSpecsValueService.query().eq("specs_id", items.getId()).list();
                if(gsGoodsSpecsValues !=null &&(!gsGoodsSpecsValues.isEmpty())){
                    items.setValues(gsGoodsSpecsValues);
                }
            });
            goodsDto.setSpecs(gsGoodsSpecsList);
        }
        List<GsGoodsSkus> gsGoodsSkusList = gsGoodsSkusService.query().eq("goods_id", id).list();
        if(gsGoodsSkusList !=null && (!gsGoodsSkusList.isEmpty())) {
            gsGoodsSkusList.forEach(items -> {
                List<GsGoodsSkusValue> gsGoodsSkusValueList = gsGoodsSkusValueService.query().eq("skus_id", items.getId()).list();
                if(gsGoodsSkusValueList!=null &&(!gsGoodsSkusValueList.isEmpty())){
                    items.setSpecs(gsGoodsSkusValueList);
                }
            });
            goodsDto.setSkus(gsGoodsSkusList);
        }
        return goodsDto;
    }

//    goodsEsService.saveEs(String goodsId);


}

